package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Slf4j注解：日志注解，添加
 */
@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    /** 1.注册功能 */
    @ApiOperation(value = "注册功能")
    @PostMapping ("reg")
    public JsonResult Reg(@RequestBody  @Validated UserRegDTO userRegDTO){
        //使用日志方法打印输出
        log.debug("userRegDTO" + userRegDTO);
        //1.确认用户是否被占用
   UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
    if (userVO!=null){
        return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
    }
    //2.存入数据表
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insetUser(user);
        return JsonResult.ok();//注册成功
    }

    /** 2.登录功能 */
    @ApiOperation(value = "登录")
    @PostMapping("login")
    private JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userLoginDTO"+ userLoginDTO);
        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO==null){//用户名错误
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (userLoginDTO.getPassword().equals(userVO.getPassword())){
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }
        //密码错误
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }

    /**3.获取用户登录功能 */
    @ApiOperation(value = "当前用户")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
     UserVO userVO  = (UserVO)  session.getAttribute("user");
     return JsonResult.ok(userVO);

    }

    /** 4.退出登录功能 */
    @ApiOperation(value = "退出登录")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }
}

